package FileCompare

import (
	"bytes"
	"io"
	"os"
)

func IsSameFile(filePath1, filePath2 string) (bool, error) {
	// 每次读取的块大小
	const chunkSize = 16 * 1024

	// 打开文件1
	file1, err := os.Open(filePath1)
	if err != nil {
		return false, err
	}
	defer file1.Close()

	// 打开文件2
	file2, err := os.Open(filePath2)
	if err != nil {
		return false, err
	}
	defer file2.Close()

	// 获得两个文件的大小
	fs1, err := file1.Stat()
	if err != nil {
		return false, err
	}
	fs2, err := file2.Stat()
	if err != nil {
		return false, err
	}
	if fs1.Size() != fs2.Size() {
		return false, err
	}

	buf1 := make([]byte, chunkSize)
	buf2 := make([]byte, chunkSize)
	for {
		size1, err1 := file1.Read(buf1)
		size2, err2 := file2.Read(buf2)

		if size1 != size2 {
			return false, err
		}

		if size1 > 0 && size2 > 0 {
			if !bytes.Equal(buf1[:size1], buf2[:size2]) {
				return false, err
			}
			continue
		}
		if err1 != nil || err2 != nil {
			// 文件结束
			if err1 == io.EOF && err2 == io.EOF {
				break
			}

			if err1 != nil {
				return false, err1
			}
			if err2 != nil {
				return false, err2
			}
		}
	}

	return true, nil
}
